package com.example.testapp;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.testapp.api.ApiClient;
import com.example.testapp.api.ApiService;
import com.example.testapp.model.BookDataUpdateRequest;
import com.example.testapp.utils.GetCategoryIcon;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class DetailActivity extends AppCompatActivity {
    private static final String TAG = "DetailActivity";
    // 添加API服务实例
    private ApiService apiService;
    private EditText categoryEditText;
    private ImageView editCategoryIcon;

    private int currentRecordId;
    private EditText amountEditText;
    private EditText recordTimeEditText;
    private EditText sourceEditText;
    private EditText remarkEditText;
    private Calendar calendar;
    private int type;
    private int userId; // 添加成员变量
    private View rootLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail); // 更新布局引用

        // 获取根布局
        rootLayout = findViewById(R.id.root_layout);
        // 初始化Retrofit服务
        apiService = ApiClient.getClient().create(ApiService.class);

        Log.i(TAG, "进入详情页面");

        // 获取传递过来的记录数据
        currentRecordId = getIntent().getIntExtra("record_id", 0);
        type = getIntent().getByteExtra("record_type", (byte) 0);
        String category = getIntent().getStringExtra("record_category");
        double price = getIntent().getDoubleExtra("record_price", 0.0);
        String date = getIntent().getStringExtra("record_date");
        String remark = getIntent().getStringExtra("record_remark");
        String source = getIntent().getStringExtra("record_source");

        // 获取用户ID
        userId = getIntent().getIntExtra("user_id", 0);
        Log.d(TAG, "onCreate: Received userId: " + userId);
        Log.d(TAG, "onCreate: 接收到的记录数据: ID=" + currentRecordId +
                ", 类型=" + type +
                ", 类别=" + category +
                ", 金额=" + price +
                ", 日期=" + date +
                ", 备注=" + remark +
                ", 来源=" + source);

        // 初始化视图并显示记录详情
        initView(currentRecordId, type, category, price, date, remark, source);
    }

    private void initView(int recordId, int type, String category, double price, String date, String remark, String source) {
        // 设置返回按钮点击事件
        ImageView backArrow = findViewById(R.id.btn_back); // 更新ID引用
        backArrow.setOnClickListener(v -> onBackPressed());

        // 设置类别编辑框
        categoryEditText = findViewById(R.id.tv_category);
        categoryEditText.setText(category);
        categoryEditText.setSingleLine(true);
        categoryEditText.setHint("点击编辑类别");

        // 设置类别编辑图标
        editCategoryIcon = findViewById(R.id.btn_edit_category);
        editCategoryIcon.setOnClickListener(v -> {
            categoryEditText.requestFocus();
            showKeyboard(categoryEditText);
        });

        // 类别编辑框监听
        categoryEditText.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                // 获得焦点时清空提示
                categoryEditText.setHint("");
                showKeyboard(categoryEditText);
            } else {
                // 失去焦点时更新图标
                updateCategoryIcon();
                // 恢复提示文本
                categoryEditText.setHint("点击编辑类别");
            }
        });

        categoryEditText.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                updateCategoryIcon();
                hideKeyboard(v);
                v.clearFocus();
                return true;
            }
            return false;
        });

        // 初始化金额编辑框
        amountEditText = findViewById(R.id.tv_amount);
        amountEditText.setText(formatAmount(price));
        amountEditText.setTextColor(getAmountColor(type));

        Button typeToggleButton = findViewById(R.id.btn_type_toggle);
        typeToggleButton.setText(this.type == 1 ? "支出" : "收入");
        Log.i(TAG, "初始化按钮，当前显示为: " + (this.type == 1 ? "支出" : "收入"));
        typeToggleButton.setOnClickListener(v -> {
            if (this.type == 1) this.type = 0;
            else this.type = 1;
            typeToggleButton.setText(this.type == 1 ? "支出" : "收入");
            amountEditText.setTextColor(getAmountColor(this.type == 1 ? 1 : 0)); // 假设 1 表示支出，0 表示收入
        });

        // 金额输入监听
        amountEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String input = s.toString();
                if (!input.isEmpty() && !input.equals("-") && !input.equals("+")) {
                    try {
                        amountEditText.setTextColor(getAmountColor(type));
                    } catch (NumberFormatException e) {
                        // 忽略格式错误
                    }
                }
            }
        });

        // 金额编辑完成处理
        amountEditText.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                if (validateAndSaveAmount()) {
                    // 验证成功后隐藏键盘并清除焦点
                    hideKeyboard(v);
                    v.clearFocus();
                }
                return true;
            }
            return false;
        });

        // 初始化日期时间
        calendar = Calendar.getInstance();
        if (date != null) {
            // 支持多种日期格式
            String[] patterns = {
                    "yyyy-MM-dd'T'HH:mm:ss",    // 带 T 的格式
                    "yyyy-MM-dd HH:mm:ss",       // 带空格的格式
                    "yyyy.MM.dd HH:mm"           // 显示格式（备用）
            };

            boolean parsed = false;
            for (String pattern : patterns) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.getDefault());
                    Date parsedDate = sdf.parse(date);
                    if (parsedDate != null) {
                        calendar.setTime(parsedDate);
                        parsed = true;
                        Log.d(TAG, "日期解析成功: 格式=" + pattern + ", 结果=" + sdf.format(parsedDate));
                        break;
                    }
                } catch (ParseException e) {
                    // 继续尝试下一种格式
                }
            }

            if (!parsed) {
                Log.e(TAG, "所有日期格式解析失败: " + date + ", 使用当前时间");
            }
        } else {
            Log.e(TAG, "日期字符串为null, 使用当前时间");
        }

        // 设置记录时间编辑框
        recordTimeEditText = findViewById(R.id.tv_record_time);
        recordTimeEditText.setText(formatDateTime());
        recordTimeEditText.setOnClickListener(v -> {
            // 确保先隐藏键盘
            hideKeyboard(v);
            showDateTimePicker();
        });

        // 设置来源编辑框
        sourceEditText = findViewById(R.id.tv_source);
        sourceEditText.setText(source);
        sourceEditText.setSingleLine(true);
        sourceEditText.setHint("点击填写来源"); // 添加提示文本
        sourceEditText.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                hideKeyboard(v);
                v.clearFocus();
                return true;
            }
            return false;
        });

        // 设置备注编辑框
        remarkEditText = findViewById(R.id.tv_remark);
        if (TextUtils.isEmpty(remark)) {
            remarkEditText.setHint("点击添加备注"); // 空值时显示提示
        } else {
            remarkEditText.setText(remark);
        }
        remarkEditText.setSingleLine(false);
        remarkEditText.setMinLines(1);
        remarkEditText.setMaxLines(3);

        // 添加备注焦点监听
        remarkEditText.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus && TextUtils.isEmpty(remarkEditText.getText().toString())) {
                // 获得焦点且内容为空时，清空提示文本
                remarkEditText.setHint("");
            } else if (!hasFocus && TextUtils.isEmpty(remarkEditText.getText().toString())) {
                // 失去焦点且内容为空时，恢复提示文本
                remarkEditText.setHint("点击添加备注");
            }
        });

        // 根据类型设置图标
         setCategoryIcon(category);

        // 设置按钮点击事件
        setupButtonListeners(recordId);

        // 设置根布局点击事件
        rootLayout.setOnClickListener(v -> {
            // 清除所有焦点并隐藏键盘
            clearAllFocus();
        });

        TextView tips = findViewById(R.id.text_detail_tips);
        // 创建处理程序
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            // 平滑消失动画
            tips.animate()
                    .alpha(0f) // 渐隐效果
                    .setDuration(500) // 动画时长
                    .withEndAction(() -> tips.setVisibility(View.GONE)) // 完成后隐藏
                    .start();
        }, 3000); // 3秒延迟
    }

    // 添加更新图标的方法
    private void updateCategoryIcon() {
        String newCategory = categoryEditText.getText().toString().trim();
        if (!TextUtils.isEmpty(newCategory)) {
            setCategoryIcon(newCategory);
            Log.d(TAG, "更新类别图标: " + newCategory);
        }
    }

    private void clearAllFocus() {
        // 清除所有输入框的焦点并隐藏键盘
        amountEditText.clearFocus();
        recordTimeEditText.clearFocus();
        sourceEditText.clearFocus();
        remarkEditText.clearFocus();
        categoryEditText.clearFocus();

        // 更新类别图标
        updateCategoryIcon();

        // 隐藏键盘
        hideKeyboard();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (v instanceof EditText) {
                Rect outRect = new Rect();
                v.getGlobalVisibleRect(outRect);
                if (!outRect.contains((int) event.getRawX(), (int) event.getRawY())) {
                    // 点击在EditText外部，清除焦点并隐藏键盘
                    v.clearFocus();
                    hideKeyboard(v);

                    // 如果是类别编辑框，更新图标
                    if (v.getId() == R.id.tv_category) {
                        updateCategoryIcon();
                    }
                }
            }
        }
        return super.dispatchTouchEvent(event);
    }

    private String formatAmount(double amount) {
        return String.format(Locale.getDefault(), "%.2f", amount);
    }

    private int getAmountColor(int type) {
        return getResources().getColor(
                type == 0 ? android.R.color.holo_green_dark : android.R.color.holo_red_dark
        );
    }

    private String formatDateTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm", Locale.getDefault());
        return sdf.format(calendar.getTime());
    }

    private void setCategoryIcon(String category) {
        ImageView categoryIcon = findViewById(R.id.iv_category); // 更新ID引用
        categoryIcon.setImageResource(GetCategoryIcon.getIconId(category));
    }

    private void setupButtonListeners(int recordId) {
        // 删除按钮点击事件
        findViewById(R.id.btn_delete).setOnClickListener(v -> { // 更新ID引用
            Log.d(TAG, "点击删除按钮，记录ID: " + recordId);
            // 显示确认对话框
            showDeleteConfirmationDialog(recordId);
        });

        // 保存按钮点击事件
        findViewById(R.id.btn_save).setOnClickListener(v -> { // 更新ID引用
            Log.d(TAG, "点击保存按钮，记录ID: " + recordId);
            saveRecordChanges(recordId);
        });

        // 编辑金额图标点击事件 - 现在直接编辑，不需要额外操作
//        findViewById(R.id.btn_edit_amount).setOnClickListener(v -> {
//            amountEditText.requestFocus();
//            showKeyboard(amountEditText);
//        });
    }

    private void showDeleteConfirmationDialog(int recordId) {
        // 创建确认对话框
        MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
        builder.setTitle("确认删除")
                .setMessage("确定要删除这条记录吗？")
                .setPositiveButton("确认", (dialog, which) -> {
                    // 执行删除操作
                    deleteRecord(recordId);
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void deleteRecord(int recordId) {
        // 这里实现删除记录的逻辑
        Log.d(TAG, "执行删除操作，记录ID: " + recordId);
        Call<Void> call = apiService.deleteBookData(recordId);
        call.enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.isSuccessful()) {
                    Log.i(TAG, "删除成功");
                    setResult(RESULT_OK);
                    finish();
                } else {
                    Log.e(TAG, "删除失败，状态码: " + response.code());
                    showToast("删除失败，请重试");
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                Log.e(TAG, "删除请求失败", t);
                showToast("网络错误，删除失败");
            }
        });
    }

    private void saveRecordChanges(int recordId) {
        // 验证金额
        if (!validateAndSaveAmount()) {
            return;
        }

        // 获取新的类别
        String newCategory = categoryEditText.getText().toString().trim();
        if (TextUtils.isEmpty(newCategory)) {
            newCategory = "其它";
        }

        // 获取修改后的数据
        String newAmount = amountEditText.getText().toString();
        BigDecimal amount = new BigDecimal(newAmount);

        // 转换日期格式
        SimpleDateFormat serverFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
        String formattedDateTime = serverFormat.format(calendar.getTime());

        // 处理来源
        String newSource = sourceEditText.getText().toString().trim();
        if (TextUtils.isEmpty(newSource)) {
            newSource = "其它";
        }

        String newRemark = remarkEditText.getText().toString();

        // 构建更新请求 - 使用正确的字段名和类型
        BookDataUpdateRequest updateRequest = new BookDataUpdateRequest();
        updateRequest.setId(recordId);
        updateRequest.setType((byte) type); // 转换为byte类型
        updateRequest.setBookDate(formattedDateTime); // 使用bookDate字段
        updateRequest.setPrice(amount); // 使用BigDecimal类型
        updateRequest.setCategory(newCategory); // 使用新类别
        updateRequest.setRemark(newRemark);
        updateRequest.setSource(newSource);
        updateRequest.setUserId(userId); // 必须设置userId
        Log.d(TAG, "saveRecordChanges: 更新请求: ID=" + recordId +
                ", 类型=" + type +
                ", 日期=" + formattedDateTime +
                ", 类别=" + newCategory +
                ", 金额=" + amount +
                ", 来源=" + newSource +
                ", 备注=" + newRemark +
                ", 用户ID=" + userId);

        // 发送更新请求
        Call<Void> call = apiService.updateBookData(updateRequest);
        call.enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.isSuccessful()) {
                    Log.i(TAG, "更新成功");
                    setResult(RESULT_OK);
                    finish();
                } else {
                    try {
                        String errorBody = response.errorBody() != null ?
                                response.errorBody().string() : "无错误信息";
                        Log.e(TAG, "更新失败，状态码: " + response.code() +
                                ", 错误信息: " + errorBody);

                        // 特殊处理400错误
                        if (response.code() == 400) {
                            showToast("请求参数错误，请检查数据格式");
                        } else {
                            showToast("更新失败，请重试");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        showToast("更新失败，请重试");
                    }
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                Log.e(TAG, "更新请求失败", t);
                showToast("网络错误，更新失败");
            }
        });
    }

    private boolean validateAndSaveAmount() {
        String amountStr = amountEditText.getText().toString();
        if (TextUtils.isEmpty(amountStr)) {
            showToast("金额不能为空");
            return false;
        }

        try {
            double amount = Double.parseDouble(amountStr);
            // 金额验证通过
            return true;
        } catch (NumberFormatException e) {
            showToast("请输入有效的金额");
            return false;
        }
    }

    private void showDateTimePicker() {
        // 创建日期选择对话框
        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this,
                (view, year, month, dayOfMonth) -> {
                    calendar.set(Calendar.YEAR, year);
                    calendar.set(Calendar.MONTH, month);
                    calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    showTimePicker();
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
        );
        datePickerDialog.show();
    }

    private void showTimePicker() {
        // 创建时间选择对话框
        TimePickerDialog timePickerDialog = new TimePickerDialog(
                this,
                (view, hourOfDay, minute) -> {
                    calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                    calendar.set(Calendar.MINUTE, minute);
                    recordTimeEditText.setText(formatDateTime());
                },
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE),
                true
        );
        timePickerDialog.show();
    }

    private void showKeyboard(View view) {
        view.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
        }
    }

    private void hideKeyboard() {
        View view = getCurrentFocus();
        if (view != null) {
            hideKeyboard(view);
        }
    }

    private void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
}